/*
**    Copyright (C) 2003-2011 Institute for Systems Biology
**                            Seattle, Washington, USA.
**
**    This library is free software; you can redistribute it and/or
**    modify it under the terms of the GNU Lesser General Public
**    License as published by the Free Software Foundation; either
**    version 2.1 of the License, or (at your option) any later version.
**
**    This library is distributed in the hope that it will be useful,
**    but WITHOUT ANY WARRANTY; without even the implied warranty of
**    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
**    Lesser General Public License for more details.
**
**    You should have received a copy of the GNU Lesser General Public
**    License along with this library; if not, write to the Free Software
**    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
*/

package org.systemsbiology.iteration;

import java.util.ArrayList;

/**
 * A quick set of utility methods for testing (restartable) {@link Iterable}{@code s}
 * @author trobinso
 */
public class IterableUtil {

	/**
	* IterableUtil is not an instantiable class, so the constructor is blocked.
	*/
	@Deprecated private IterableUtil(){
		throw new UnsupportedOperationException("IterableUtil is a static method library, not a real object.");
	}

    /**
     * Returns a count of the elements in an {@link Iterable}, in linear time
     * @param itrbl {@link Iterable} supplied by the caller
     * @return int number of elements indexed by this {@link Iterable}
     * @throws IllegalArgumentException if the supplied Iterable was null
     */
    public static int count(Iterable<?> itrbl) {
        if (itrbl == null) {
            throw new IllegalArgumentException("Supplied Iterable object was null");
        }

        int i = 0;
        for (Object o: itrbl) {
            ++i;
        }
        return i;
    }
    
    /**
     * Returns an array representation of the objects referenced in this {@link Iterable}, in linear time
     *
     *  If the supplied Iterable was null, this method will simply return null.
     *
     *  Note that the array representation is created by reference. As a result, changes to data contained in the array
     *  may write through to contents indexed by the original {@link Iterable}.
     * @param itrbl {@link Iterable} supplied by the caller
     * @return int number of elements indexed by this {@link Iterable}
     */
    public static <T> Object[] asArray(Iterable<T> itrbl) {
        if (itrbl == null) {
            return null;
        }

        ArrayList<T> a = new ArrayList<T>();
        for (T o: itrbl) {
            a.add(o);
        }
        return a.toArray();
    }
}
